package cn.azr.domain.strategy.service.rule.chain.factory;

import cn.azr.domain.strategy.model.entity.StrategyEntity;
import cn.azr.domain.strategy.repository.IStrategyRepository;
import cn.azr.domain.strategy.service.rule.chain.ILogicChain;
import cn.azr.types.common.Constants;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * ClassName:DefaultChainFactory
 * Description:
 *
 * @version 1.0
 * @Author azr
 * @Create 2024/10/15 11:05
 */
@Service
public class DefaultChainFactory {


    //自动注入所有责任链节点
    private final Map<String, ILogicChain> logicChainMap;


    private final IStrategyRepository strategyRepository;

    public DefaultChainFactory(Map<String, ILogicChain> map, IStrategyRepository strategyRepository) {
        this.logicChainMap = map;
        this.strategyRepository = strategyRepository;
    }

    public ILogicChain openLogicChain(Long strategyId){
        //获取rule_models
        StrategyEntity strategy = strategyRepository.queryEntityByStrategyId(strategyId);
        String ruleModels = strategy.getRuleModel();

        //无抽奖规则 走默认流程
        if(null==ruleModels||0==ruleModels.length()){
            return logicChainMap.get("default");
        }
        String[] ruleModel = ruleModels.split(Constants.SPLIT);
        //获取第一个责任链节点返回
        ILogicChain logicChain= logicChainMap.get(ruleModel[0]);
        ILogicChain cur=logicChain;
        //构建责任链 添加节点
        for (int i = 1; i < ruleModel.length; i++) {
            //append添加时同时向后☞
            cur=cur.appendNext(logicChainMap.get(ruleModel[i]));
        }

        //最后添加兜底策略
        cur.appendNext(logicChainMap.get("default"));

        return logicChain;

    }

}
